import { useJwt } from "@vueuse/integrations/useJwt";
import { useCookies } from "@vueuse/integrations/useCookies";

export default defineNuxtRouteMiddleware((to, from) => {
  const userStore = useMyUserStore();

  if (import.meta.client) {
    if (!userStore.isLogin) {
      console.log("not login");
      return navigateTo("/login");
    }
    const token = useCookie("Authorization");
    if (!token.value) {
      console.log("bad token");
      return navigateTo("/login");
    }
    else {
      const { payload } = useJwt<JwtPayLoad & JwtWithTimeOut>(token.value);
      // jwt 解码错误 或 jwt 过期
      if (!payload.value || payload.value.exp < Date.now() / 1000) {
        // TODO: 删除 cookie (在服务端)
        // setCookie(event, "Authorization", { maxAge: 0 })
        console.log("jwt超时");
        return navigateTo("/login");
      }
      // jwt 中的 email 与 userStore 中的 email 不一致
      else if (payload.value.email !== userStore.data.email) {
        const cookie = useCookies(["Authorization"]);
        cookie.set("Authorization", "", { maxAge: 0 });
        console.log("jwt不匹配");
        // !但是可能以后可能会是为登录请求
        return navigateTo("/login");
      }
    }
  }
});
